﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ESPL.CodeGenerator.Domain.ProjectBuilders;
using ESPL.CodeGenerator.Domain;
using ESPL.CodeGenerator.Common.Structs;
using ESPL.CodeGenerator.Common.Enums;
using ESPL.CodeGenerator.Common.ProjectBuilders;
using Ionic.Zip;
using System.IO;
using ESPL.CodeGenerator.Domain.Utilities;
using System.Xml;
using System.Diagnostics;
using LinqToEdmx.Model.Conceptual;
using LinqToEdmx.Model.Storage;
using LinqToEdmx.Map;
using LinqToEdmx;

namespace ESPL.CodeGenerator.WindowsApp
{
    public partial class frmMainForm : Form
    {
        public frmMainForm()
        {
            InitializeComponent();
            openFileDialog.Filter = "(*.edmx)|*.edmx";
            openFileDialog.FilterIndex = 1;
            openFileDialog.Multiselect = false;
        }

        private void btnGenerate_Click(object sender, EventArgs e)
        {
            if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string directoryPath = System.IO.Path.GetDirectoryName(openFileDialog.FileName);
                var projectBuilder = CodeGeneratorFactory.CreateInstance().CreateProjectBuilder(GetConfig(directoryPath, openFileDialog.SafeFileName));
                InitializeProjectTree(projectBuilder);
            }
        }

        private void InitializeProjectTree(ICodeBuilder projectBuilder)
        {
            var output = string.Empty;
            foreach (var requestItem in projectBuilder.InitializeProjectTree())
            {
                output = string.Format("{0}\n{1}", output, requestItem.Output);
            }
            rtbOutput.Text = output;
            string directoryPath = System.IO.Path.GetDirectoryName(openFileDialog.FileName);
            ZipHelper.ZipFolder(string.Format("{0}\\{1}", directoryPath, tbxAppName.Text), directoryPath, string.Format("{0}.zip", tbxAppName.Text));
        }

        private IEnumerable<EntityType> GetEntities()
        {
            if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                var edmx = Edmx.Load(openFileDialog.FileName);

                // Get the EntityTypes from the conceptual model
                var entityTypes = edmx.GetItems<EntityType>();
                return entityTypes;
                //var count1 = entityTypes.Count();

                //// Get the EntityTypeStores from the storage model
                //var entityTypeStores = edmx.GetItems<EntityTypeStore>();
                //var count2 = entityTypeStores.Count();//Should().Equal(28);

                //// Get the EntityTypeMappings from the mappings
                //var entityTypeMappings = edmx.GetItems<EntityTypeMapping>();
                //var count3 = entityTypeMappings.Count();//.Should().Equal(26);
            }
            return null;
        }

        private ApplicationConfiguration GetConfig(string filePath, string fileName)
        {
            var path = System.IO.Path.Combine(filePath, fileName);
            var edmx = Edmx.Load(path);
            var entityTypes = edmx.GetItems<EntityType>();

            return new ApplicationConfiguration()
            {
                CompanyNameAbbrevation = tbxCompanyAbbrevation.Text,
                ApplicationName = tbxAppName.Text,
                DestinationPath = tbxDestinationPath.Text.Replace('\\', '/'),
                IncludeCommon = true,
                IncludeData = true,
                IncludeDataTransfer = true,
                IncludeDomain = true,
                IncludeMVC5 = true,
                IncludePresentation = true,
                EdmxFilePath = filePath,
                EdmxFileName = fileName,
                Entities = entityTypes,
                VisualStudioVersion = GetVisualStudioVersion()
            };
        }

        private VisualStudioVersion GetVisualStudioVersion()
        {
            if (cbxVersion.SelectedItem.Equals("VS2010"))
                return VisualStudioVersion.VS2010;
            if (cbxVersion.SelectedItem.Equals("VS2013"))
                return VisualStudioVersion.VS2013;
            if (cbxVersion.SelectedItem.Equals("VS2015"))
                return VisualStudioVersion.VS2015;

            return VisualStudioVersion.None;
        }

        private void frmMainForm_Load(object sender, EventArgs e)
        {
            cbxVersion.SelectedIndex = 1;
        }

        private void btnBrowseDestPath_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                tbxDestinationPath.Text = folderBrowserDialog.SelectedPath;
            }
        }

        private void btnUnzip_Click(object sender, EventArgs e)
        {
            //if(openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            //{
            //    byte[] buffer = new byte[2048];
            //    int n;
            //    using (var input = new ZipInputStream(openFileDialog.FileName))
            //    {
            //        ZipEntry entry;
            //        while ((entry = input.GetNextEntry()) != null)
            //        {
            //            if (entry.IsDirectory)
            //            {
            //                DirectoryHelper.CreateDirectory(string.Format("D:/Temp/Unzip/{0}",entry.FileName));
            //            }
            //            else
            //            {
            //                string outputPath = Path.Combine("D:/Temp/Unzip", entry.FileName);
            //                using (var output = File.Open(outputPath, FileMode.Create, FileAccess.ReadWrite))
            //                {
            //                    while ((n = input.Read(buffer, 0, buffer.Length)) > 0)
            //                    {
            //                        output.Write(buffer, 0, n);
            //                    }
            //                }
            //            }
            //        }
            //    }

            //}
            //XmlDataDocument xmldoc = new XmlDataDocument();
            //XmlNodeList xmlnode;
            //int i = 0;
            //string str = null;
            //FileStream fs = new FileStream("Samples/SampleInputOfClasses.xml", FileMode.Open, FileAccess.Read);
            //xmldoc.Load(fs);
            //xmlnode = xmldoc.GetElementsByTagName("Entity");
            //for (i = 0; i <= xmlnode.Count - 1; i++)
            //{
            //    xmlnode[i].ChildNodes.Item(0).InnerText.Trim();
            //    var properties = xmldoc.GetElementsByTagName("property");
            //    var attrbts = properties[0].Attributes;
            //    //str = xmlnode[i].ChildNodes.Item(0).InnerText.Trim() + "  " + xmlnode[i].ChildNodes.Item(1).InnerText.Trim() + "  " + xmlnode[i].ChildNodes.Item(2).InnerText.Trim();
            //    //MessageBox.Show(str);
            //}
        }
    }
}
